package scm;

import java.net.*;
import java.io.*;
import biz.source_code.base64Coder.*;

public class Email
{
    private String _email;
    private String _message;
    private String _subject;

    private String _smtpHost = "smtp.wp.pl";
    private String _smtpLogin = "scmscm";
    private String _smtpPassword = "scmscm123";
    private String _smtpEmail = "scmscm@wp.pl";

    public Email(String email, String subject, String message)
    {
        _email = email;
        _message = message;
        _subject = subject;
    }

    public void send()
    {                
        String codeLogin = Base64Coder.encodeString(_smtpLogin);
        String codePassword = Base64Coder.encodeString(_smtpPassword);

        try
        {
            Socket client = new Socket(_smtpHost, 587);
            InputStream input = client.getInputStream();
            OutputStream output = client.getOutputStream();
            in(input);

            out(output, "HELO Scm");
            in(input);
            
            out(output, "AUTH LOGIN");
            in(input);
            
            out(output, codeLogin);
            in(input);

            out(output, codePassword);
            in(input);

            out(output, "MAIL FROM: <" + _smtpEmail + ">");
            in(input);

            out(output, "RCPT TO: <" + _email + ">");
            in(input);

            out(output, "DATA");
            in(input);

            out(output, "From: <" + _smtpEmail + ">");
            out(output, "To: " + _email);
            out(output, "Subject: " + _subject);
            out(output, "Content-Type: text/html; charset=utf-8");            
            out(output, "");

            out(output, _message);
            out(output, ".");

            in(input);
            out(output, "QUIT");
            input.close();
            output.close();
            client.close();            
        }
        catch(IOException e)
        {
            
        }
    }

    private void out(OutputStream output, String text) throws IOException
    {
        output.write((text +"\r\n").getBytes());
    }

    private void in(InputStream input) throws IOException
    {
        int character = 0;
        while(character != '\n')
        {
            character = input.read();
            //System.out.print((char)character);
        }
    }
}